from flask import Blueprint
from flask import request,redirect,url_for,render_template,g
from .forms import QuestionForm,AnswerForm
from models import QuestionModel,AnswerModel
from exts import db
from decorators import login_required
from sqlalchemy import text
bp = Blueprint('qa', __name__, url_prefix="/")

@bp.route('/')
def index():
    questions = QuestionModel.query.order_by(text('-create_time')).all()
    return render_template('index.html',questions=questions)

@bp.route("qa/answer_public",methods=['POST'])
@login_required
def answer_public():
    form = AnswerForm(request.form)
    if form.validate():
        content = form.content.data
        question_id = form.question_id.data
        answer = AnswerModel(content=content,question_id=question_id,author=g.user)
        db.session.add(answer)
        db.session.commit()
        return redirect(url_for("qa.qa_detail",qa_id=question_id))
    else:
        print(form.errors)
        return redirect(url_for("qa.qa_detail",qa_id=request.form.get("question_id")))

@bp.route("qa/qa_detail/<qa_id>")
def qa_detail(qa_id):
    question = QuestionModel.query.get(qa_id)
    return render_template('detail.html',question=question)

@bp.route('/qa/public',methods = ['GET','POST'])
@login_required
def public_question():
    if request.method == 'GET':
        return render_template('public_question.html')
    else:
    #用户id可以拿session里面的
    #表单要认证
        form = QuestionForm(request.form)
        if form.validate():
            title = form.title.data
            content = form.content.data
            question = QuestionModel(title=title,content=content,author=g.user)
            db.session.add(question)
            db.session.commit()
            return redirect("/")
        else:
            print(form.errors)
            return redirect(url_for("qa.public_question"))


@bp.route("/qa/search")
def search():
    #/search?q=xxx
    q = request.args.get("q")
    question = QuestionModel.query.filter(QuestionModel.title.contains(q)).all()
    return render_template('index.html',questions=question)

